package com.zahb.qadx.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by Zdw on 2020/10/30 14:14
 */
public final class JsonUtil {

    private static Gson mG;
    private static JsonParser mParser;

    private static void initG() {
        if (mG == null) {
            synchronized (JsonUtil.class) {
                if (mG == null) {
                    mG = new GsonBuilder()
                            .serializeNulls()// 序列化null
                            .create();
                    mParser = new JsonParser();
                }
            }
        }
    }

    public static Gson getGson() {
        initG();
        return mG;
    }

    public static JsonParser getParser() {
        initG();
        return mParser;
    }

    public static JsonObject getJsonObject(Object object) {
        initG();
        String json = mG.toJson(object);
        return mParser.parse(json).getAsJsonObject();
    }

    public static RequestBody getRequestBody(Map<String, Object> params) {
        initG();
        return RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), mG.toJson(params));
    }
}
